<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <template #header>
        <el-input
          placeholder="请输入内容"
          v-model="queryInfo.query"
          clearable
          @clear="initUserList"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="initUserList"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="addDialogVisible = true"
          >添加用户</el-button
        >
      </template>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="80px"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <!-- {{ row }} -->
            <el-switch v-model="row.mg_state" @change="userStateChange(row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEdit(row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClosed"
    >
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesDialogVisible"
      width="50%"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <br />
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <br />
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserListApi,
  userStateChangeApi,
  addUserApi,
  showEditApi,
  changeEditApi,
  delUserApi,
  getRolesListApi,
  saveRolesApi,
} from "@/api/user";
export default {
  name: "UsersIndex",
  data() {
    return {
      tableData: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      queryInfo: {
        pagenum: 1,
        pagesize: 2,
        query: "",
      },
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addFormRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度需要在2到10之间",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 15,
            message: "长度需要在6到15之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            pattern:
              /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            message: "请输入合法的邮箱",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号码",
            trigger: "blur",
          },
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: "请输入合法的手机号",
            trigger: "blur",
          },
        ],
      },
      editForm: {},
      setRolesDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      //已选中的角色id值
      selectedRoleId: "",
    };
  },
  methods: {
    async initUserList() {
      const res = await getUserListApi(this.queryInfo);
      // console.log(res);
      this.tableData = res.data.users;
      this.total = res.data.total;
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
    },

    handleSizeChange(currentSize) {
      // console.log(currentSize);
      this.queryInfo.pagesize = currentSize;
      this.initUserList();
    },
    handleCurrentChange(currentPage) {
      // console.log(currentPage);
      this.queryInfo.pagenum = currentPage;
      this.initUserList();
    },
    async userStateChange(userinfo) {
      // console.log(userinfo);
      const res = await userStateChangeApi(userinfo.id);
      // console.log(res);
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        this.$message.error("更新状态失败！");
      }
      this.$message.success("更新状态成功！");
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    async addUser() {
      this.$refs.addFormRef.validate();
      const res = await addUserApi(this.addForm);
      // console.log(res);
      if (res.meta.status !== 201) {
        this.$message.error("添加用户失败");
      }
      this.$message.success("添加用户成功");
      this.addDialogVisible = false;
      this.initUserList();
    },
    async showEdit(id) {
      this.editDialogVisible = true;
      // console.log(id);
      const res = await showEditApi(id);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败");
      }
      this.editForm = res.data;
    },
    editClosed() {
      this.$refs.editFormRef.resetFields();
    },
    async editUserInfo() {
      await this.$refs.editFormRef.validate();
      const res = await changeEditApi(this.editForm.id, {
        email: this.editForm.email,
        mobile: this.editForm.mobile,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("更新用户信息失败");
      }
      this.editDialogVisible = false;
      this.initUserList();
      this.$message.success("更新用户信息成功");
    },
    async delUser(id) {
      try {
        await this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        const res = await delUserApi(id);
        if (res.meta.status !== 200) {
          return this.$message.error("删除用户失败！");
        }
        this.$message.success("删除用户成功！");
        this.initUserList();
      } catch (error) {
        // console.log(error);
        this.$message.info("已取消删除");
      }
    },
    async setRoles(userInfo) {
      this.userInfo = userInfo;
      const res = await getRolesListApi();
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      // this.$message.success("获取列表成功！");
      this.rolesList = res.data;
      this.setRolesDialogVisible = true;
    },
    async saveRolesInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色");
      }
      const res = await saveRolesApi(this.userInfo.id, {
        rid: this.selectedRoleId,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("更新角色失败!");
      }
      this.$message.success("更新角色成功!");
      this.initUserList();
      this.setRolesDialogVisible = false;
    },
  },
  created() {
    this.initUserList();
  },
};
</script>

<style lang="scss" scoped>
.users {
  .el-breadcrumb {
    margin-bottom: 15px;
  }
  .el-card {
    .el-input {
      width: 33%;
      margin-right: 20px;
    }
    .el-table {
      margin-bottom: 15px;
    }
  }
}
</style>
